package main.java.DMDE.persistence;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import main.java.DMDE.model.*;
import main.java.common.IXmlManager;

public class AttributeXmlManager implements IXmlManager<Attribute> {

	private TypeXmlManager typeManager = new TypeXmlManager();
	private ModifierXmlManager modifierManager = new ModifierXmlManager();
	
	
	public Element getElementFromItem(Attribute parameter, Document document) {
		Element typeElement = document.createElement("attribute");
		typeElement.setAttribute("name", parameter.getName().toString());
		typeElement.setAttribute("visibility", parameter.getVisibility() != null ? parameter.getVisibility().getType() : Visibility.PUBLIC.getType());
		typeElement.appendChild(typeManager.getElementFromItem(parameter.getType(), document));
		Element modifiers = document.createElement("modifiers");
		for (Modifier modifier : parameter.getModifiers()) {
			if (modifier != null)
				modifiers.appendChild(modifierManager.getElementFromItem(modifier, document));
		}
		typeElement.appendChild(modifiers);
		return typeElement;
	}

	@Override
	public Attribute getItemFromXmlElement(Element element) throws Exception {
		Attribute attribute = new Attribute();
		attribute.setName(element.getAttribute("name"));
		attribute.setVisibility(getVisibility(element.getAttribute("visibility")));
		attribute.setType(typeManager.getItemFromXmlElement((Element) element.getElementsByTagName("type").item(0)));
		NodeList modifiers = element.getElementsByTagName("modifiers").item(0).getChildNodes();
		for (int i = 0; i < modifiers.getLength(); i++) {
			Node node = modifiers.item(i);
			if (node == null || !(node instanceof Element))
				continue;
			Element modifierElement = (Element) node;
			attribute.addModifier(modifierManager.getItemFromXmlElement(modifierElement));
		}
		return attribute;
	}
	
	private Visibility getVisibility(String visibility) {
		if (Visibility.PUBLIC.getType().equals(visibility))
			return Visibility.PUBLIC;
		if (Visibility.PRIVATE.getType().equals(visibility))
			return Visibility.PRIVATE;
		if (Visibility.PROTECTED.getType().equals(visibility))
			return Visibility.PROTECTED;
		return Visibility.PUBLIC;
	}
}
